﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raspare;
using Xamarin.Forms;

namespace SharedMobilePlatform
{
	public class AbilityPage : ContentPage
	{
	    private ListView listView;

	    public List<Tuple<string, int>> listOfAbilities;

	    public bool ShowAllAbilities = false;

        public AbilityPage(Karaktär Character)
        {
            Title = "Färdigheter";
            if (Application.Current.Properties.ContainsKey("ShowAllAbilities"))
                ShowAllAbilities = (bool)Application.Current.Properties["ShowAllAbilities"];

            listOfAbilities = GetAbilityList(Character);
            
            listView = new Xamarin.Forms.ListView()
            {
                RowHeight = 40,
                ItemsSource = listOfAbilities.Select( item => item.Item1)
            };

		    listView.ItemTapped += RollDie;

			Content = new StackLayout {
				Children = {
                    listView
				}
			};
		}

	    private void RollDie(object sender, ItemTappedEventArgs e)
	    {
            var input =  listOfAbilities.First(item => item.Item1.Equals(e.Item.ToString()));

            int value = input.Item2;
            Random rnd = new Random();
            int firstRoll = rnd.Next(1, 11);
            int secondRoll = 0;
            if (firstRoll == 10)
            {
                firstRoll = 10;
                secondRoll = rnd.Next(1, 11);
            }
            if (firstRoll == 1)
            {
                firstRoll = 0;
                secondRoll = -rnd.Next(1, 11);
            }
            int diceResult = value + firstRoll + secondRoll;
            string diceRoll = "[" + (firstRoll == 0 ? 1 : firstRoll) + (secondRoll != 0 ? "," + secondRoll : "") + "]";
            
            DisplayAlert("Tärningsslag", input.Item1 + ": " + diceRoll + " " + diceResult, "OK");

            ((ShowCharacterPage)Parent).AddToHistory(input.Item1 + ": " + diceRoll + " " + diceResult);
	    }

	    private List<Tuple<string, int>> GetAbilityList(Karaktär character)
	    {
	        var result = new List<Tuple<string, int>>();
            foreach (var färdighet in character.Färdigheter.Where(färd => färd.Värde > 0 || ShowAllAbilities))
	        {
	            string namn = färdighet.Namn;
	            if (färdighet.Specialiseringar != null && färdighet.Specialiseringar.Any())
	            {
	                namn += " (" + String.Join(", ", färdighet.Specialiseringar) + ")";
	            }
	            namn += " " + färdighet.Värde;
	            result.Add(new Tuple<string, int>(namn, färdighet.Värde));
	        }
            return result;
	    }
	}
}
